package com.shu.aop;

import com.shu.annotaion.DataSourceName;
import com.shu.domain.constant.DataSourceConstant;
import com.shu.domain.context.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by shu on 2017/9/8.
 */
@Component
@Aspect
public class DataSourceAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("execution(* com.shu.dao.impl..*.*(..))")
    public void pointCut(){
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
        MethodSignature methodSignature = null;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;

        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());

        DataSourceName datasource = currentMethod.getAnnotation(DataSourceName.class);
        if(datasource != null){
            DataSourceContextHolder.setDB(datasource.value());
            LOGGER.info("设置数据源为：" + datasource.value());
        }else{
            DataSourceContextHolder.setDB(DataSourceConstant.MASTER_DATASOURCE);
            LOGGER.info("设置数据源为："+DataSourceConstant.MASTER_DATASOURCE);
        }

        try {
            return point.proceed();
        } finally {
            LOGGER.info("清空数据源信息！");
            DataSourceContextHolder.clearDB();
        }
    }




}
